/*
 * Copyright (c) 2018, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.config;

import java.time.LocalDateTime;
import java.util.Objects;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

/**
 * @author guilu
 * @date 2018年12月3日
 */
@Component
@ConditionalOnMissingBean(MetaObjectHandler.class)
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private static String CREATE_TIME = "createTime";
    private static String MODIFY_TIME = "modifyTime";
    
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        if (Objects.isNull(createTime)) {
            this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
        }
        Object updateTime = getFieldValByName(MODIFY_TIME, metaObject);
        if (Objects.isNull(updateTime)) {
            this.setFieldValByName(MODIFY_TIME, LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName(MODIFY_TIME, metaObject);
        if (Objects.isNull(updateTime)) {
            this.setFieldValByName(MODIFY_TIME, LocalDateTime.now(), metaObject);
        }
    }

}
